import re

import MySQLdb
import requests

# 打开数据库连接
db = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="hdk021009", db="ax_database", charset="utf8")

# 使用cursor()方法获取操作游标
cursor = db.cursor()

url = "https://www.baidu.com"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
}
res = requests.get(url, headers=headers)
text = res.text
compile = re.compile(r'<span class="title-content-title">(?P<name>.*?)</span>', re.S)
data = compile.finditer(text)
# 使用execute方法执行SQL语句
cursor.execute("drop table if exists baidu_resou")
cursor.execute("create table baidu_resou(id int,name varchar(50))")

key = 1
for i in data:
    # 使用execute方法执行SQL语句
    sql = "insert into baidu_resou values (%d,\'%s\')" % (key, i.group('name'))
    cursor.execute(sql)
    key += 1

res.close()
# 同步到数据库中
db.commit()
# 关闭数据库连接
db.close()

print('over.')


